var uploadPlugin = function ( setting ) {

    var swfu;
    var obj = this;

    this.init = function () {
        swfu = new SWFUpload({
            file_size_limit:setting['file_size_limit'],
            file_types:setting['file_types'],
            post_params:{'cookie_auth':setting['cookie_auth']},
            upload_url:host + '/admin/?c=attachment&a=upload',
            flash_url:host + '/content/swfupload/swfupload.swf',
            flash9_url:host + '/content/swfupload/swfupload_fp9.swf',
            button_placeholder_id:"SWFUploadButton",

            file_queued_handler:this.file_queued_function, //文件选择后
            file_queue_error_handler:this.file_queue_error_function, //文件选择后出错
            file_dialog_complete_handler:this.file_dialog_complete_function, //文件选择后(多少文件添加进来)
            upload_start_handler:this.upload_start_function, //上传前
            upload_progress_handler:this.upload_progress_function, //上传进行中
            upload_error_handler:this.upload_error_function, //上传错误
            upload_success_handler:this.upload_success_function, //上传成功，还没有保存
            upload_complete_handler:this.upload_complete_function //真正上传成功，上载的数据已经保存，可又上传下一个文件了（如果有）
        });

        this.initHtml();
        this.optionEvent();
    }

    this.initHtml = function(){
        var html = '<div class="upload_box" style="display: none;">\
                        <div class="upload-queue" id="upload-queue" style="padding: 10px;">\
                            <div style="text-align: right; margin-bottom: 5px;">\
                                <button class="start btn btn-success">开始上传</button>\
                                <button class="cancel btn btn-danger">取消上传</button>\
                                <button class="close btn btn-inverse">关闭</button>\
                            </div>\
                            <table cellpadding="1" cellspacing="1" width="100%" border="0">\
                                <tr>\
                                    <th>文件名</th>\
                                    <th width="12%">大小</th>\
                                    <th width="15%">进度</th>\
                                    <th width="15%">状态</th>\
                                    <th width="26%">操作</th>\
                                </tr>\
                            </table>\
                        </div>\
                    </div>';
        $( 'body' ).append( html );
    }

    this.optionEvent = function(){
        $( ".add, .thumb, .del" ).live( 'click', function (e) {
            var o = $( this );
            if ( o.hasClass( 'disabled' ) ) {
                return false;
            }
            var c = o.attr( 'class' ).split( ' ' )[0];
            var fun = obj[c];
            fun( o, o.parent().parent() );
            return false;
        });

        $( ".start" ).live( 'click', function () {
            if ( swfu.getStats().files_queued <= 0 ) {
                $.jBox.tip( '请先添加文件' );
                return false;
            }
            swfu.startUpload();
        });

        $( ".cancel,.close" ).live( 'click', function () {
            obj.close_box();
        });
    }

    this.close_box = function(){
        swfu.cancelUpload();
        $.jBox.close();
        obj.initHtml();
    }

    this.file_queued_function = function ( file ) {
        var data = $( "#upload-queue" ).find( 'table' );

        var fileSize = Math.round(file.size / 1024);
        var suffix   = 'KB';
        if (fileSize > 1000) {
            fileSize = Math.round(fileSize / 1000);
            suffix   = 'MB';
        }
        var fileSizeParts = fileSize.toString().split('.');
        fileSize = fileSizeParts[0];
        if (fileSizeParts.length > 1) {
            fileSize += '.' + fileSizeParts[1].substr(0,2);
        }
        fileSize += suffix;

        var html = '<tr class="upload-item" id="' + file.id + '">' +
            '<td>' + file.name + '</td>' +
            '<td>' + fileSize + '</td>' +
            '<td class="progress"><div class="progress-bar"><div class="swfupload-progress-bar"></div></td>' +
            '<td class="status">等待上传</td>' +
            '<td class="option" style="border-right: none;">' +
            '<button class="add btn btn-mini btn-success disabled" title="添加到文章内容中">添加</button>' +
            '<button class="thumb btn btn-mini btn-info disabled" title="设置为缩略图">缩略图</button>' +
            '<button class="del btn btn-mini btn-danger disabled">删除</button>' +
            '</td>' +
            '<td style="display: none;" class="data"><div class="id"></div><div class="file"></div><div class="img"></div></td>' +
            '</tr>';
        data.append( html ).fadeIn();
    }

    this.file_queue_error_function = function ( file, code, message ) {
        switch ( code ) {
            case -100:
                $.jBox.tip("一次最多允许选择个 " + swfu.getSetting('file_upload_limit') + " 文件！");
                break;
            case -110:
                $.jBox.tip("最大允许选择 " + swfu.getSetting('file_size_limit') + " 的文件！");
                break;
            case -120:
                $.jBox.tip("您选择的文件是0字节！");
                break;
            case -130:
                $.jBox.tip("您选择的文件类型不正确！");
                break;
        }
    }

    this.file_dialog_complete_function = function ( selected, queued, total ) {
        if ( selected > 0 && queued > 0 && selected - queued <= 0 ) {
            var html = $( ".upload_box" ).html();
            var option = {
                title:'上传文件',
                width:650,
                showClose:false,
                buttons:{}
            }
            $.jBox( html, option );

            $( "#upload-queue table tr:last td" ).css( 'border-bottom', 'none' );
            $( ".upload_box" ).remove();
        }
    }

    this.upload_success_function = function ( file, data, response ) {
        var data_obj = eval( '(' + data + ')' );

        if (  data_obj.file == 'error' ) {
            $( "#" + file.id ).find( ".status" ).html( data_obj.file + ": 错误" );
            $( "#" + file.id ).find( ".swfupload-progress-bar" ).css( "width", "1px" );
            return;
        }

        $( "#" + file.id ).find( ".status" ).html( '完成' );
        $( "#" + file.id ).find( ".data .file" ).html( data_obj.file );
        $( "#" + file.id ).find( ".data .img" ).html( data_obj.img );
        $( "#" + file.id ).find( ".data .id" ).html( data_obj.id );
        $( "#" + file.id ).find( ".option:button" ).removeClass( 'disabled' );

        // 写入表单数据
        var attach = $( 'input[name="attach[id]"]' );
        var val = $.trim( attach.val() );
        attach.val( data_obj.id + "," + val );
    }

    this.upload_progress_function = function ( file, bytesComplete, bytesTotal ) {
        var p = Math.round( bytesComplete / bytesTotal * 100 );
        $( "#" + file.id ).find( ".swfupload-progress-bar" ).css( "width", p + "%" );
        $( "#" + file.id ).find( ".status" ).html( p + "%" );
    }

    this.upload_complete_function = function (file) {
        if ( swfu.getStats().files_queued > 0 ) {
            swfu.startUpload();
            return;
        }
        $.jBox.tip( '上传完成', 'success' );
        $( ".add, .thumb, .del" ).removeClass( 'disabled' );
    }

    this.upload_error_function = function ( file, code, message ) {
        switch ( code ) {
            case -200:
                $.jBox.tip( "服务器错误！" );
                break;
            case -210:
                $.jBox.tip( "找不到上传路径！" );
                break;
            case -220:
                $.jBox.tip( "可能是上传目录没有权限！" );
                break;
            case -230:
                $.jBox.tip( "安全错误，上传违反了安全约束！" );
                break;
            case -240:
                $.jBox.tip( "上传文件的数量超过了限定的值！" );
                break;
            case -250:
                $.jBox.tip( "尝试初始化上传时出现了错误！" );
                break;
            case -260:
                $.jBox.tip( "没有找到要上传的文件！" );
                break;
            case -270:
                $.jBox.tip( "未知错误！" );
                break;
            case -290:
                $.jBox.tip( "暂停了文件”" + file.name + "“的上传！" );
                break;
        }
    }

    this.add = function( a, b ){
        var img = b.find( ".img" ).html();
        var file = img == 1 ? b.find( ".file" ).html() : id;
        var html = obj.formatEditHtml( img, file );
        insert( html );
    }

    this.del = function( a, b ){
        var id = b.find( ".id" ).html();
        var url = host + '/admin/?c=attachment&a=del&id=' + id;
        swfu.cancelUpload( b.attr( 'id' ), true );
        $.get( url, function ( result ) {
            if( result == 'success'){
                // 删除表单数据
                var attach = $( 'input[name="attach[id]"]' );
                var new_id = attach.val().replace( id + ',', "" );
                attach.val( new_id );

                // 删除编辑器数据
                if ( typeof editor1 == "undefined" ) {
                    return false;
                }
                if ( editor1.designMode != false ) {
                    $.jBox.tip( '请先将编辑器切换到可视化模式!' );
                    return false;
                }
                var html = editor1.html();
                var img = b.find( ".img" ).html();
                var file = img == 1 ? b.find( ".file" ).html() : id;
                var src = obj.formatEditHtml( img, file );

                var newHTML = html.replaceAll( src, '' );
                editor1.html( newHTML );
            }
        });

        b.fadeOut( 2000, function () {
            b.remove();
            if( $(".upload-item" ).size() <= 0 ){
                obj.close_box();
            }
        });
    }

    this.thumb = function( a, b ){
        var id = b.find( ".id" ).html();
        var img = b.find( ".img" ).html();
        if ( img == 0 ){
            jBox.tip( "只有图片才能设置缩略图!" );
            return;
        }
        var obj = $( 'input[name="article[thumb]"]' );
        obj.val( b.find( ".data .file" ).html() );
    }

    this.formatEditHtml = function( type, file ){
        if( type == 1 ){
            file = host + '/' +  file;
            return '<img src="' + file + '" />';
        }
        return "[attach=" + file + "]";
    }
}